'use strict';

import { agentjoinModel } from "../model/agentjoin";
import { ServiceBase, Exceptions } from '../kalend';
import { common } from "../middleware/common";
import { usertokenService } from "./usertoken";
var moment = require('moment');

class AgentjoinService extends ServiceBase {
    constructor() {
        super(agentjoinModel)
    }
    async query(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const appbegintime = params.appbegintime;
        const appendtime = params.appendtime;
        const iscontact = params.iscontact;
        const filter: any = {};
        if (appbegintime) {
          filter.createTime = { '$gte': new Date(moment(new Date(appbegintime)).format('YYYY-MM-DD') + '  00:00:00') };
      }
      if (appendtime) {
          if (filter.createTime) {
              filter.createTime['$lte'] = new Date(moment(new Date(appendtime)).format('YYYY-MM-DD') + '  23:59:59');
          } else {
              filter.createTime = { '$lte': new Date(moment(new Date(appendtime)).format('YYYY-MM-DD') + '  23:59:59')};
          }
      }
     
        if (iscontact && iscontact != '') {
            filter.iscontact = iscontact;
        }

        let result: any = await this.queryPagination(offset, limit, {
            filter: filter,
            sort: { createtime: -1 }
        });

        result.rows = result.rows.map((item: any) => {
            if (item.iscontact == '0') {
                item.iscontact = '未联系';
            } else if (item.iscontact == '1') {
                item.iscontact = '已联系';
            }
            return item;
        });

        return result;
    }

    async updatestatus(doc: any) {
        return this.update(doc._id, { iscontact: doc.iscontact,remarks:doc.remarks });
    }

    async querybyid(doc: any) {
      return this.querySingle({_id:doc._id});
  }

    async save(doc: any) {
        if (!doc.token) {
            throw Exceptions.notoken();
        }
        const sesiondata = await usertokenService.getToken(doc.token);
        if (sesiondata) {
            doc.userid = sesiondata.userid;
            delete doc.token;
            const isexists = await this.querySingle({ phone: doc.phone, name: doc.name });
            if (isexists) {
                this.update(isexists._id, doc);
                //return `已申请，邀请码为【${isexists.valite}】`;
            } else {
                //doc.code = this.buildcode();
                //按规则生成验证码后发送短信
                // let validation = Math.round(Math.random() * 1000000).toString();
                // if (validation.length < 6) {
                //     for (let i = 6 - validation.length; i > 0; i--) {
                //         validation = '0' + validation;
                //     }
                // }
                // doc.valite = validation;
                this.create(doc);
                //return `申请成功，邀请码为【${doc.valite}】`;;
            }
            return `保存成功`;
        } else {
            throw Exceptions.known('未找到用户信息，保存失败');
        }
    }
    async buildcode() {
        let code = common.buildCode(6);
        const isexists = await this.exist({ valite: code });
        if (!isexists) {
            return code;
        } else {
            await this.buildcode();
        }
    }

    async queryByCode(token: any) {
        if (!token) {
            throw Exceptions.notoken();
        }
        const sesiondata = await usertokenService.getToken(token);
        if (sesiondata) {
            return this.querySingle({ userid: sesiondata.userid });
        } else {
            throw Exceptions.known('未找到用户信息，查询失败');
        }
    }
}

export const agentjoinService = new AgentjoinService();